package admin

import (
	// "net/url"
	"strconv"

	controllers "github.com/cn-joyconn/goadmin/controllers"
	"github.com/cn-joyconn/goutils/array"
	"github.com/cn-joyconn/goutils/strtool"

	// "github.com/cn-joyconn/goadmin/middleware/auth"
	adminModel "github.com/cn-joyconn/goadmin/models/admin"
	"github.com/cn-joyconn/goadmin/models/global"
	adminServices "github.com/cn-joyconn/goadmin/services/admin"
	"github.com/gin-gonic/gin"
)

type UserPermissionController struct {
	controllers.BaseController
}

var AdminUserPermissionService *adminServices.AdminUserPermissionService

func init() {
	AdminUserPermissionService = &adminServices.AdminUserPermissionService{}
}

/**
 * 获取用户的所有角色
 *
 * @param appids
 * @return
 */
//  @RequestMapping(value = "getMyRoles", method= RequestMethod.GET)
//  @IAuthorization(needPermission = false)
func (controller *UserPermissionController) GetMyRoles(c *gin.Context) {
	uid := controller.GetContextUserId(c)
	if global.IsSuperAdmin(uint64(uid)) {		
		_, _models, _ := adminRoleService.SelectByPage(0, "", 1, 10000000)
		controller.ApiSuccess(c, "", _models)
	}else{

		models := AdminUserPermissionService.GetUserRoles(uid)
		controller.ApiSuccess(c, "", models)
	}
}

/**
 * 根据用户ID获取用户的角色信息
 *
 * @param fUserid
 * @return
 */
func (controller *UserPermissionController) SelectUserRoles(c *gin.Context) {
	//int appid, String fUserid
	fId := c.DefaultQuery("fUserid","")
	fUserid, err1 := strconv.ParseUint(fId, 10, 64)
	// fUserid, err1 := strconv.Atoi(fId)
	if err1 != nil {
		controller.ApiErrorCode(c, "参数错误", "", global.ParamsError)
		return
	}
	models := AdminUserPermissionService.GetUserRoles(adminModel.Juint64(fUserid))
	controller.ApiSuccess(c, "", models)
}

/**
 * 修改用户的角色信息
 *
 * @param record
 * @return
 */
func (controller *UserPermissionController) UpdateUserRolesByPrimaryKey(c *gin.Context) {
	curUserId := controller.GetContextUserId(c)
	var xAdminUserRoleLimit *adminModel.XAdminUserRoleLimit
	err := c.ShouldBindJSON(&xAdminUserRoleLimit)
	if err != nil {
		controller.ApiErrorCode(c, "参数错误", err.Error(), global.ParamsError)
		return
	}
	
	PRoleObjs :=make([]*adminModel.XAdminRoleLimit ,0)
	notExisitRoleIDs := make([]*adminModel.XAdminRoleLimit,0)	
	exisit := false
	if 	 global.IsSuperAdmin(uint64(curUserId)){
		for _,roleObj := range xAdminUserRoleLimit.PRoleObjs{
			PRoleObjs = append(PRoleObjs, roleObj)
		}
	}else{
		curUserRoles:=adminUserService.GetUserRolesByUid(curUserId.ToString())
		exisit = false
		for _,roleObj := range xAdminUserRoleLimit.PRoleObjs{
			exisit=false
			for _,userRoleObj := range *curUserRoles{
				exisit=false
				if userRoleObj.Role == roleObj.Role {
					exisit = true
					break
				}
			}
			if exisit{
				PRoleObjs = append(PRoleObjs, roleObj)
			}else{
				notExisitRoleIDs = append(notExisitRoleIDs, roleObj)
			}
		}
	}
	
	if len(notExisitRoleIDs)>0{
		userRoles:=adminUserService.GetUserRolesByUid(xAdminUserRoleLimit.UserID.ToString())
		for _,roleObj := range xAdminUserRoleLimit.PRoleObjs{
			exisit=false
			for _,userRoleObj := range *userRoles{
				exisit=false
				if userRoleObj.Role == roleObj.Role {
					exisit = true
					break
				}
			}
			if exisit{
				PRoleObjs = append(PRoleObjs, roleObj)
			}
		}
	}
	result := adminUserService.UpdateUserRoles(xAdminUserRoleLimit.UserID, &PRoleObjs)
	if result > 0 {
		controller.ApiSuccess(c, "修改成功", result)
	} else if result==0{
		controller.ApiErrorCode(c, "未修改任何内容", result,global.NoAffected)
	} else {
		controller.ApiError(c, "修改失败", result)
	}
}

/**
 * 获取用户的权限列表
 *
 * @return
 */
func (controller *UserPermissionController) GetUserRights(c *gin.Context) {
	appID := c.DefaultQuery("appid","0")
	appid, err1 := strconv.Atoi(appID)
	if err1 != nil {
		controller.ApiErrorCode(c, "参数错误", "", global.ParamsError)
		return
	}
	uid := controller.GetContextUserId(c)
	models := AdminUserPermissionService.GetUserResourceIDs(appid,uid)
	controller.ApiSuccess(c, "", &models)
}

/**
 * 获取用户的菜单
 *
 * @param request
 * @return
 */
func (controller *UserPermissionController) GetMyMenuByID(c *gin.Context) {
	//int menuID, HttpServletRequest request
	fId := c.Query("menuID")
	menuID, err1 := strconv.Atoi(fId)
	if err1 != nil {
		controller.ApiErrorCode(c, "参数错误", "", global.ParamsError)
		return
	}
	uid := controller.GetContextUserId(c)
	// fUserid, _ := strconv.Atoi(uid)
	menuModels := MenuService.SelectMenuByMenuID(menuID)
	List := make([]adminModel.AdminMenu, 0)
	isSuperAdmin := global.IsSuperAdmin(uint64(uid))
	appidPermissonMap := make(map[int][]string)
	var arr []string
	var ok bool
	for _, model := range menuModels {
		if !strtool.IsBlank(model.PPermission){
			arr,ok	 = appidPermissonMap[model.PPid]
			if !ok{
				arr = make([]string, 0)
			}
			appidPermissonMap[model.PPid]=append(arr,model.PPermission)
		}
	}
	if !isSuperAdmin{
		for appid,permissions:=range  appidPermissonMap{		
			permissions=AdminUserPermissionService.HasPathPermissin(uid,appid,permissions)
			appidPermissonMap[appid]=permissions
		}
		
	}
	
	var permissions []string
	for _, model := range menuModels {
		permissions = appidPermissonMap[model.PAppid]
		if isSuperAdmin || array.InStrArray(model.PPermission, permissions) {
			List = append(List, model)
			// if model.PPid == 0 {
			// 	result = &model
			// }
		}
	}

	result := AdminUserPermissionService.ListMenu2Tree(menuModels)
	controller.ApiSuccess(c, "", result)

}
